<template>
  <div>
    <el-card style="width: 50%; margin: 0 auto;">
      <el-form ref="formRef" :model="user" :rules="rules" label-width="120px" style="padding-right: 20px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="user.username" disabled></el-input>
        </el-form-item>

        <el-form-item label="原始密码" prop="password">
          <el-input show-password v-model="user.password" placeholder="请输入原始密码"></el-input>
        </el-form-item>

        <el-form-item label="新密码" prop="newPassword">
          <el-input show-password v-model="user.newPassword" placeholder="请输入新密码"></el-input>
        </el-form-item>

        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input show-password v-model="user.confirmPassword" placeholder="请再次输入新密码"></el-input>
        </el-form-item>

        <div style="text-align: center">
          <el-button type="primary" @click="updatePassword">确认修改</el-button>
          <el-button @click="resetForm">重置</el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import request from '@/utils/request'

export default {
  name: "Password",
  data() {
    // 密码强度验证
    const validatePassword = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入密码'));
      } else if (value.length < 6) {
        callback(new Error('密码长度不能小于6位'));
      } else if (!/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[^]{6,20}$/.test(value)) {
        callback(new Error('密码必须包含大小写字母和数字'));
      } else {
        callback();
      }
    };

    // 确认密码验证
    const validateConfirmPassword = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请确认密码'));
      } else if (value !== this.user.newPassword) {
        callback(new Error('两次输入的密码不一致'));
      } else {
        callback();
      }
    };

    return {
      user: {
        username: '',
        password: '',
        newPassword: '',
        confirmPassword: ''
      },
      rules: {

        password: [
          { required: true, message: '请输入原始密码', trigger: 'blur' },
          { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
        ],
        newPassword: [
          { validator: validatePassword, trigger: 'blur' }
        ],
        confirmPassword: [
          { validator: validateConfirmPassword, trigger: 'blur' }
        ]
      }
    };
  },
  created() {
    // 从localStorage加载用户信息
    const userInfo = JSON.parse(localStorage.getItem('user-Info') || '{}');
    this.user.username = userInfo.username || '';
  },
  methods: {
    updatePassword() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          // 打印用户对象，查看传递的数据
          console.log('传递给后端的数据：', this.user);
          request({
            url: '/user/updatepassword',
            method: 'put',
            data: this.user
          }).then(res => {
            if (res.code === 200) {
              this.$message.success('密码修改成功，请重新登录');
              // 清理登录状态
              localStorage.removeItem('user-info');
              localStorage.removeItem('token');
              this.$router.push('/login');
            } else {
              this.$message.error(res.msg || '密码修改失败');
            }
          }).catch(err => {
            this.$message.error('系统错误，请稍后重试');
          });
        }
      });
    },
    resetForm() {
      this.$refs.formRef.resetFields();
    }
  }
};
</script>
